# https://pysimplegui.readthedocs.io/en/latest/cookbook/#launch-a-program-with-a-button
import PySimpleGUI as sg
import time
import os


def pid_write():
    with open('{}.pid'.format(__file__), 'w') as f:
        f.write(str(os.getpid()))
def pid_read():
    pid_file = '{}.pid'.format(__file__)
    if os.path.exists(pid_file):
        with open(pid_file, 'r') as f:
            return int(f.read())
    else:
        return 0
def pid_remove():
    os.remove('{}.pid'.format(__file__))
def pid_check():
    import psutil
    pid = pid_read()
    if pid:
        # print(f'pid read: {pid}')
        if pid in psutil.pids():
            import sys
            sys.exit()
    else:
        # print(f'pid write: {pid}')
        pid_write()
pid_check()


sg.theme('Default1')
print(sg.theme_list())
# print(sg.theme_previewer())
default_work_path = os.path.join(os.path.expanduser('~'), 'Downloads')

# menu_def = ['BLANK', ['&Open', '---', '&Save', ['1', '2', ['a', 'b']], '&Properties', 'E&xit']]
# # tray = sg.SystemTray(menu=menu_def, filename=r'default_icon.ico')
# tray = sg.SystemTray(menu=menu_def, data_base64=sg.DEFAULT_BASE64_ICON)

layout = [
    # [sg.Text('主题列表:')],
    # [sg.Listbox(values=sg.theme_list(), size=(40, 12), key='-LIST-', enable_events=True)],
    # [sg.Text('工作目录管理:', font=('Helvetica', 12), justification='left')],
    [
        sg.Text('工作目录管理', justification='left', font=(44)),
        # sg.Text('', size=(40, 1), justification='Center', key='text_show_time')
    ],
    [sg.Text('配置:', justification='right')],
    [
        sg.Text('    download:', justification='right'),
        sg.InputText(key='input_text_download'),
        sg.FolderBrowse('Browse'),
        sg.Button('更新', key='btn_input_cfg_download'),
        sg.Text('', justification='left', key='input_text_download_tip', text_color='red')
    ],
    [sg.Text('    path:       '), sg.Text(default_work_path, key='show_cfg_download', size=(60, 1))],
    [sg.Text('创建:', justification='left')],
    [
        sg.Radio("chengyun", group_id='radio_create', key='radio_createPath_chengyun', size=(8, 1), default=True),
            sg.Button('Create', key='btn_createPath_chengyun'),
            sg.Button('Open', key='btn_openPath_chengyun'),
        sg.Radio("idp", group_id='radio_create', key='radio_createPath_idp', size=(4, 1), pad=((50, 0), (0, 0))),
            sg.Button('Create', key='btn_createPath_idp'),
            sg.Button('Open', key='btn_openPath_idp'),
    ],
    [
        sg.Radio("aws", group_id='radio_create', key='radio_createPath_aws', size=(8, 1)),
            sg.Button('Create', key='btn_createPath_aws'),
            sg.Button('Open', key='btn_openPath_aws'),
        sg.Radio("tmp", group_id='radio_create', key='radio_createPath_tmp', size=(4, 1), pad=((50, 0), (0, 0))),
            sg.Button('Create', key='btn_createPath_tmp'),
            sg.Button('Open', key='btn_openPath_tmp'),
    ],
    [
        sg.Radio("感知器", group_id='radio_create', key='radio_createPath_gzq', size=(8, 1)),
            sg.Button('Create', key='btn_createPath_gzq'),
            sg.Button('Open', key='btn_openPath_gzq'),
        sg.Radio("aliyun", group_id='radio_create', key='radio_createPath_aliyun', size=(4, 1), pad=((50, 0), (0, 0))),
            sg.Button('Create', key='btn_createPath_aliyun'),
            sg.Button('Open', key='btn_openPath_aliyun'),
    ],
    [sg.Text(' ' * 80, size=(1, 1))],
    [sg.Text('记录:', justification='left')],
    [sg.Output(size=(80, 5), key='-OUTPUT-')],
    # [sg.In(key='-IN-')],
    # [
    #     sg.Button('创建', button_color=('white', 'blue'), size=(6, 1)),
    #     sg.Cancel()
    # ]
    [sg.Button('Clear'), sg.Cancel()]
]

# win = sg.Window('诗和远方', layout, no_titlebar=True, alpha_channel=.9, grab_anywhere=True)
win = sg.Window('诗和远方', layout, alpha_channel=.9, grab_anywhere=False, font=("Helvetica", 10), icon='favicon.ico')


def run_time():
    return time.strftime('%Y%m%d_%H:%M:%S', time.localtime())

def create_dir(dir):
    try:
        os.makedirs(dir)
        print('{} 创建目录完成.[{}]'.format(run_time(), dir))
    except FileExistsError:
        sg_popup_error('目录 [{}] 已存在!!!'.format(dir))
    except PermissionError:
        sg_popup_error('项目目录权限不足[{}]!!!'.format(dir))
    except Exception as e:
        sg_popup_error('创建目录 [{}] 失败!!![{}]'.format(dir, e))

def open_dir(dir):
    try:
        os.startfile(dir)
    except FileNotFoundError:
        sg_popup_error('项目目录不存在[{}]!!!'.format(dir))
    except PermissionError:
        sg_popup_error('项目目录权限不足[{}]!!!'.format(dir))
    except Exception as e:
        sg_popup_error('打开项目录 [{}] 失败!!![{}]'.format(dir, e))

def sg_popup_error(err_text):
    print('{} {}'.format(run_time(), err_text))
    sg.popup_error(err_text, grab_anywhere=False, keep_on_top=True)


while True:
    now_date = time.strftime('%Y%m%d', time.localtime())

    # menu_item = tray.read()
    # print(menu_item)
    # if menu_item == 'Exit':
    #     break
    # elif menu_item == 'Open':
    #     sg.popup('Menu item chosen', menu_item)

    event, values = win.read()
    # print('{} 当前值： {} = {}'.format(time.strftime('%Y%m%d_%H:%M:%S', time.localtime()), event, values))
    # print('{} win： {}'.format(time.strftime('%Y%m%d_%H:%M:%S', time.localtime()), win))
    if event in (sg.WIN_CLOSED, 'Cancel'):
        pid_remove()
        break

    # win['text_show_time'].update(time.time())

    # 更新路径
    if event == 'btn_input_cfg_download':
        if values['input_text_download'] == '':
            sg_popup_error('路径不能为空!!!')
        download_path = values['input_text_download']
        print('{} 更新路径: {}'.format(run_time(), values['input_text_download']))
        win['show_cfg_download'].update(download_path)
        default_work_path = download_path

    # 创建目录
    sp_event = event.split('_')
    if len(sp_event) > 2 and sp_event[-2] == 'createPath':
        prod_name = sp_event[-1]
        if values["radio_createPath_{}".format(prod_name)]:
                # or values["checkbox_createPath_{}".format(prod_name)]
            print('{} 已选择 {}'.format(run_time(), prod_name))
            work_dir_name = "{}_{}".format(now_date, prod_name)
            print('{} 目录 {}'.format(run_time(), work_dir_name))
            work_path = os.path.join(default_work_path, work_dir_name)
            print('{} 创建目录 {}'.format(run_time(), work_path))
            create_dir(work_path)
        else:
            sg_popup_error('请选择要创建的项目名称!!![{}] !!!'.format(prod_name))
    # 打开目录
    elif len(sp_event) > 2 and sp_event[-2] == 'openPath':
        prod_name = sp_event[-1]
        print('{} 已选择 {}'.format(run_time(), prod_name))
        work_dir_name = "{}_{}".format(now_date, prod_name)
        print('{} 目录 {}'.format(run_time(), work_dir_name))
        work_path = os.path.join(default_work_path, work_dir_name)
        print('{} 打开路径: {}'.format(run_time(), work_path))
        open_dir(work_path)


    # 清理日志
    if event == 'Clear':
        win['-OUTPUT-'].update('')

    # sg.Print(f"选择: {values['-LIST-'][0]}", text_color='', background_color='', font='')
    # sg.ProgressBar(10, orientation='h', size=())



win.close()



